#include "train.h"
#include<sys/sendfile.h>
int transferFile(int sfd,const char*filename){
    
    //先判断文件是否存在
    off_t file_exit = 0;
    train_t train;
    memset(&train, 0, sizeof(train_t));
    // recvn(sfd, &train.len, 4);
    //  recvn(sfd, &file_exit, train.len);
    //  printf("file_exit=%ld\n", file_exit);

    // memset(&train, 0, sizeof(train_t));
    printf("filename=%s strlen=%ld %d\n",filename,strlen(filename),(int)filename[4]);
    int fd = open(filename, O_RDONLY);
    if (fd == -1)
    {
        printf("puts error\n"); //本地不存在此文件
        train.length = -1;
        sendn(sfd, &train, 4);
        return 1;    
    }
    train.length = 1;
    int sret = sendn(sfd, &train, 4);
    printf("---send %d byte\n",sret);

    struct stat file_status;
    memset(&file_status, 0, sizeof(file_status));
    fstat(fd, &file_status);
    off_t file_size = file_status.st_size - file_exit;
    memset(&train, 0, sizeof(train));
    memcpy(train.data, &file_size, sizeof(file_size));
    train.length = sizeof(file_size);
    sendn(sfd, &train, train.length + 4);

    int ret, left = file_size, cur = 0;
    while (left > 0)
    {
        memset(&train, 0, sizeof(train));
        ret = read(fd, train.data, sizeof(train.data));
        if (ret == 0)
        {
            printf("read error\n");
        }
        train.length = ret;
        ret = sendn(sfd, &train, 4 + train.length);
        cur += train.length;
        left -= train.length;
    }
    printf("send_file send file success\n");
    
}

